package com.xzcs.quartz.weixin;

import com.xzcs.mapper.weixin.WeiXinAccountMapper;
import com.xzcs.quartz.JobTask;
import com.xzcs.util.Constants;
import com.xzcs.util.common.StringUtils;
import com.xzcs.util.spring.PropertyUtils;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WeixTokenTaskImpl implements JobTask {

	@Override
	public void run(PropertyUtils propertyUtils) throws Exception {
		WeiXinAccountMapper weiXinAccountMapper = (WeiXinAccountMapper)propertyUtils.getSpringBean("weiXinAccountMapper");
		String fileRoot = propertyUtils.getPropertyValue(Constants.DEFAULT_FILE_UPLOAD_PATH);
		List<Map<String, Object>> list = weiXinAccountMapper.findWeixAccounts(new HashMap<String, Object>());
		for (Map<String, Object> acct:list) {
			String accountId = StringUtils.get(acct, "account_id");
			WxMpService wxService = this.getWxMpService(weiXinAccountMapper, accountId);
			wxService.getAccessToken(false);
			String accessToken = wxService.getWxMpConfigStorage().getAccessToken();
			long expiresTime = wxService.getWxMpConfigStorage().getExpiresTime();
			Map<String, Object> params1 = new HashMap<String, Object>();
			params1.put("accessToken", accessToken);
			params1.put("expiresTime", expiresTime);
			params1.put("accountId", accountId);
			weiXinAccountMapper.updateAccessToken(params1);
		}
	}

	public WxMpService getWxMpService(WeiXinAccountMapper weiXinAccountMapper, String accountId){
		Map<String, Object> weixAccount = weiXinAccountMapper.findWeixAccount(accountId);
		WxMpInMemoryConfigStorage wxMpConfigStorage = new WxMpInMemoryConfigStorage();
		wxMpConfigStorage.setAppId(StringUtils.get(weixAccount, "appid")); // 设置微信公众号的appid
		wxMpConfigStorage.setSecret(StringUtils.get(weixAccount, "appsecret")); // 设置微信公众号的app corpSecret
		wxMpConfigStorage.setToken(StringUtils.get(weixAccount, "token")); // 设置微信公众号的token
		wxMpConfigStorage.setAesKey(StringUtils.get(weixAccount, "aeskey")); // 设置微信公众号的EncodingAESKey
		wxMpConfigStorage.setAccessToken(StringUtils.get(weixAccount, "access_token"));
		wxMpConfigStorage.setExpiresTime(StringUtils.toLong(StringUtils.get(weixAccount, "expires_time")));
		WxMpService wxService = new WxMpServiceImpl();
		wxService.setWxMpConfigStorage(wxMpConfigStorage);
		return wxService;
	}
}
